<?php
/**
 * 飞书通讯录服务
 */
namespace service;

use service\GuardService;
use think\Cache;
use think\Exception;
use think\Request;
use think\Db;

class FeishuService
{
    private $api_fs_url = "https://open.feishu.cn/open-apis";
    private $app_id = "cli_a5389a15df79500b";
    private $app_secret = "tRnBtBaz9lFdYjHMXNmnScuMWAkW6iMK";

    const ENCRYPTKEY = "y6PHQydNcDwp84SU2uxyMhTAo0AbTVMS";

    private $count = 1;

    private $page_size = 50;

    private $redirect_uri = "https://elevatorc.gtcloud.cn/index/passport/login";

    protected $tenant_access_token_key = "tenant_access_token";
    protected $tenant_access_token = null;
    protected $app_access_token_key = "app_access_token";
    protected $app_access_token = null;

    protected $app_access_ticket_key = "app_access_ticket";
    protected $app_access_ticket = null;

    /**
     * @var object 对象实例
     */
    protected static $instance;

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return \think\Request
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }


    /**
     * 通讯录token
     * @return mixed
     */
    public function GetappAccessToken()
    {
        $this->app_access_token = Cache::store('redis')->get($this->app_access_token_key);
        //dump($this->app_access_token);exit;
        if (empty($this->app_access_token)) {
            $client = new \GuzzleHttp\Client();
            $token_url = $this->api_fs_url."/auth/v3/app_access_token/internal";
            $data = [
                "app_id" => $this->app_id,
                "app_secret" => $this->app_secret
            ];
            $response = $client->request('POST', $token_url, ['json' => $data]);
            $jsonToArray = json_decode($response->getBody()->getContents(), true);
            //dump($jsonToArray);exit;
            if($jsonToArray['code'] == 0){
                Cache::store('redis')->set($this->app_access_token_key, $jsonToArray['app_access_token'], $jsonToArray['expire']);
                $this->app_access_token = $jsonToArray['app_access_token'];
            }
        }
        return $this->app_access_token;
    }

    /**
     * 通讯录token
     * @return mixed
     */
    public function GettenantAccessToken()
    {
        $this->tenant_access_token = Cache::store('redis')->get($this->tenant_access_token_key);
        if (empty($this->tenant_access_token)) {
            $client = new \GuzzleHttp\Client();
            $token_url = $this->api_fs_url."/auth/v3/tenant_access_token/internal";
            $data = [
                "app_id" => $this->app_id,
                "app_secret" => $this->app_secret
            ];
            $response = $client->request('POST', $token_url, ['json' => $data]);
            $jsonToArray = json_decode($response->getBody()->getContents(), true);
            if($jsonToArray['code'] == 0){
                Cache::store('redis')->set($this->tenant_access_token_key, $jsonToArray['tenant_access_token'], $jsonToArray['expire']);
                $this->tenant_access_token = $jsonToArray['tenant_access_token'];
            }
        }
        return $this->tenant_access_token;
    }

    public function GetTicket(){
        $this->app_access_ticket = Cache::store('redis')->get($this->app_access_ticket_key);
        $this->app_access_ticket = null;
        if (empty($this->app_access_ticket)) {
            $this->GettenantAccessToken();
            $client = new \GuzzleHttp\Client();
            $token_url = $this->api_fs_url . "/jssdk/ticket/get";
            $headers = [
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => 'Bearer ' . $this->tenant_access_token
            ];
            $response = $client->request('POST', $token_url, ['headers' => $headers]);
            $jsonToArray = json_decode($response->getBody()->getContents(), true);
            //dump($jsonToArray);exit;
            if($jsonToArray['code'] == 0){
                Cache::store('redis')->set($this->app_access_ticket_key, $jsonToArray['data']['ticket'], $jsonToArray['data']['expire_in']);
                $this->app_access_ticket = $jsonToArray['data']['ticket'];
            }
        }
        return $this->app_access_ticket;
    }

    public function Getparameters(){
        $this->GetTicket();
        $microtime = microtime(true);
        $timestamp = round($microtime * 1000);
        $nonceStr  = $this->createNonceStr();
        $domain = request()->domain();
        if(isHttps() || strpos($domain,'elevatorc.gtcloud.cn') !== false){
            $http = "https://";
        }
        else{
            $http = "http://";
        }
        //$http= (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$http$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $str = "jsapi_ticket={$this->app_access_ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($str);
        return [
            'appid' => $this->app_id,
            'signature' => $signature,
            'jsapi_ticket' => $this->app_access_ticket,
            'noncestr' => $nonceStr,
            'timestamp' => $timestamp,
            'url' => $url
        ];
    }

    public function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str   = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function GetUserfloorinfo($user_id){
        //return ["7F","9F","10F","12F","13F"];
        //首先取个人设置的，如果没有设置再取所属部门的，如果所属部门的没有，就取上级部门的，直到遍历到最顶级10000000
        $u_floorinfo = Db::name("user")->where(['user_id'=>$user_id])->value("floorinfo");
        //dump($u_floorinfo);exit;
        if(empty($u_floorinfo)){
            $u_floorinfo = [];
            $department_lists = Db::name("user")->alias("u")->join("so_department d","d.is_jtzb = 1 and find_in_set(d.department_id,u.department_ids)")->field("d.department_id,d.floorinfo,d.pid")->where(["u.user_id"=>$user_id])->select();
            //dump($department_lists);exit;
            foreach ($department_lists as $department_list){
                if(!empty($department_list['floorinfo'])){
                    $u_floorinfo[] = $department_list['floorinfo'];
                }
            }
            if(empty($u_floorinfo)){
                foreach ($department_lists as $department_list){
                    $pid = $department_list['pid'];
                    $d_flag = true;
                    while ($d_flag && !in_array($pid,getdepartmentids())){
                        $dinfo = Db::name("department")->where(['department_id'=>$pid])->find();
                        if(!empty($dinfo['floorinfo'])){
                            $u_floorinfo[] = $dinfo['floorinfo'];
                            $d_flag = false;
                        }
                        $pid = $dinfo['pid'];
                    }
                }
            }
        }
        if(is_array($u_floorinfo)){
            $u_floorinfo = implode(",",array_filter($u_floorinfo));
        }
        if(!empty($u_floorinfo)){
            $u_floorinfo = array_unique(explode(",",$u_floorinfo));
        }
        else{
            $u_floorinfo = ["7F","9F","10F","12F","13F"];
        }
        return $u_floorinfo;
    }

    /**
     * 获取用户信息
     * @param $code
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function GetUserinfo($code = ''){
        //获取user_access_token
        $this->GettenantAccessToken();
        $client = new \GuzzleHttp\Client();
        $token_url = $this->api_fs_url."/authen/v1/oidc/access_token";
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $data = [
            "grant_type" => "authorization_code",
            "code" => $code
        ];
        $response = $client->request('POST', $token_url, ['json' => $data,'headers' => $headers]);
        $jsonToArray = json_decode($response->getBody()->getContents(), true);
        //dump($jsonToArray);exit;
        if($jsonToArray['code'] == 0 && isset($jsonToArray['data']) && !empty($jsonToArray['data'])){
            $user_url = $this->api_fs_url.'/authen/v1/user_info';
            $headers = [
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => 'Bearer '.$jsonToArray['data']['access_token']
            ];
            $request = $client->get($user_url, [
                'headers' => $headers
            ]);
            $userinfo = json_decode($request->getBody()->getContents(),true);
            //return $userinfo;
            if($userinfo['code'] == 0){
                return $userinfo['data'];
            }
            else{
                exit($userinfo['message']);
            }
        }
        else{
            exit($jsonToArray['message']);
        }
    }

    public function GetLogincodeurl(){
        $scope = urlencode("contact:contact.base:readonly contact:contact:readonly_as_app");
        $this->redirect_uri = urlencode($this->redirect_uri);
        $code_url = $this->api_fs_url."/authen/v1/authorize?app_id={$this->app_id}&redirect_uri={$this->redirect_uri}&scope={$scope}&state=login";
        //echo $code_url;exit;
        return $code_url;
    }

    public function GetDeparmentlists(){
        $this->GettenantAccessToken();
        //获取集团总部的部门信息
        $department_ids = getdepartmentids();
        $bach_url = $this->api_fs_url.'/contact/v3/departments/batch?department_id_type=department_id&user_id_type=user_id';
        foreach ($department_ids as $key => $department_id){
            $bach_url .= "&department_ids={$department_id}";
        }
        $client = new \GuzzleHttp\Client();
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $request = $client->get($bach_url, [
            'headers' => $headers
        ]);
        $department_lists = json_decode($request->getBody()->getContents(),true);
        $result = [];
        if(isset($department_lists['data']['items'])){
            $result = $department_lists['data']['items'];
        }
        return $result;
    }

    public function QueryUser($user_id){
        $resdata = ['code'=>400,'message'=>'failed','data'=>[]];
        $this->GettenantAccessToken();
        $user_url = $this->api_fs_url."/contact/v3/users/{$user_id}?department_id_type=department_id&user_id_type=user_id";
        $client = new \GuzzleHttp\Client();
        try {
            $headers = [
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => 'Bearer '.$this->tenant_access_token
            ];
            $request = $client->get($user_url, [
                'headers' => $headers
            ]);
            $userinfos = json_decode($request->getBody()->getContents(),true);
            if($userinfos['code'] == 0 && isset($userinfos['data']['user']) && !empty($userinfos['data']['user'])){
                $main_department_list = $userinfos['data']['user'];
                $resdata['code'] = 200;
                $resdata['message'] = 'success';
                $resdata['data']['user_id'] = $main_department_list['user_id'];
                $resdata['data']['username'] = $main_department_list['name'];
                $resdata['data']['mobile_origin'] = $main_department_list['mobile'];
                $resdata['data']['mobile'] = str_replace('+86','',$main_department_list['mobile']);
            }
        }
        catch (\GuzzleHttp\Exception\RequestException $e) {
            //dump($e);exit;
            if ($e->hasResponse()) {
                $exceptionResponse = $e->getResponse();
                //$statusCode = $exceptionResponse->getStatusCode();
                $errorMessage = $exceptionResponse->getReasonPhrase();
                //$error = $e->getMessage();
                $resdata['message'] = $errorMessage;
                // 处理错误信息
                //echo "HTTP错误：状态码 {$statusCode}，原因：{$errorMessage}，原因：{$error}";
            } else {
                // 处理可能的连接问题
                $resdata['message'] = "连接失败，错误信息：{$e->getMessage()}";
                //echo "连接失败，错误信息：{$e->getMessage()}";
            }
        }
        return $resdata;
    }

    public function AddEditUser($user_id,$type=''){
        $this->GettenantAccessToken();
        $user_url = $this->api_fs_url."/contact/v3/users/{$user_id}?department_id_type=department_id&user_id_type=user_id";
        $client = new \GuzzleHttp\Client();
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $request = $client->get($user_url, [
            'headers' => $headers
        ]);
        $userinfos = json_decode($request->getBody()->getContents(),true);
        //dump($userinfos['data']['user']);exit;
        if($userinfos['code'] == 0 && isset($userinfos['data']['user']) && !empty($userinfos['data']['user'])){
            $main_department_list = $userinfos['data']['user'];
            $ctime = time();
            $main_dep_data = [];
            $main_dep_data['user_id'] = $main_department_list['user_id'];
            $main_dep_data['username'] = $main_department_list['name'];
            $main_dep_data['open_id'] = $main_department_list['open_id'];
            $main_dep_data['union_id'] = $main_department_list['union_id'];
            //$main_dep_data['mobile_origin'] = $main_department_list['mobile'];
            //$main_dep_data['mobile'] = str_replace('+86','',$main_department_list['mobile']);
            if (isset($main_department_list['mobile']) && !empty($main_department_list['mobile'])) {
                $main_dep_data['mobile_origin'] = $main_department_list['mobile'];
                $main_dep_data['mobile'] = str_replace('+86', '', $main_department_list['mobile']);
            } else {
                $main_dep_data['mobile'] = "";
                //dump($main_department_list);exit;
            }
            $main_dep_data['mobile_visible'] = $main_department_list['mobile_visible'] ? 1 : 0;
            $main_dep_data['department_ids'] = isset($main_department_list['department_ids']) && !empty($main_department_list['department_ids']) ? implode(",",$main_department_list['department_ids']) : '';
            //头像
            if(isset($main_department_list['avatar']) && !empty($main_department_list['avatar'])){
                $main_dep_data['avatar_origin'] = isset($main_department_list['avatar']['avatar_origin']) ? $main_department_list['avatar']['avatar_origin'] : '';
                $main_dep_data['avatar_240'] = isset($main_department_list['avatar']['avatar_240']) ? $main_department_list['avatar']['avatar_240'] : '';
                $main_dep_data['avatar_640'] = isset($main_department_list['avatar']['avatar_640']) ? $main_department_list['avatar']['avatar_640'] : '';
                $main_dep_data['avatar_72'] = isset($main_department_list['avatar']['avatar_72']) ? $main_department_list['avatar']['avatar_72'] : '';
            }
            //排序
            if(isset($main_department_list['orders']) && !empty($main_department_list['orders'])){
                Db::name("user_orders")->where(['user_id'=>$main_department_list['user_id']])->update(['update_state'=>0]);
                foreach ($main_department_list['orders'] as $order){
                    $order_data = [];
                    $order_data['user_id'] = $main_department_list['user_id'];
                    $order_data['department_id'] = $order['department_id'];
                    $order_data['department_order'] = $order['department_order'];
                    $order_data['is_primary_dept'] = $order['is_primary_dept'] ? 1 : 0;;
                    $order_data['user_order'] = $order['user_order'];
                    $order_data['update_state'] = 1;
                    //dump($order_data);exit;
                    $orderinfo = Db::name("user_orders")->where(['user_id'=>$order_data['user_id']])->where(['department_id'=>$order_data['department_id']])->find();
                    if(!empty($orderinfo)){
                        Db::name("user_orders")->where(['id'=>$orderinfo['id']])->update($order_data);
                    }
                    else{
                        Db::name("user_orders")->insert($order_data);
                    }
                }
            }
            $main_dep_data['employee_no'] = $main_department_list['employee_no'];
            $main_dep_data['employee_type'] = $main_department_list['employee_type'];
            $main_dep_data['job_title'] = $main_department_list['job_title'];
            $main_dep_data['join_time'] = $main_department_list['join_time'];
            if(isset($main_department_list['leader_user_id']) && !empty($main_department_list['leader_user_id'])){
                $main_dep_data['leader_user_id'] = $main_department_list['leader_user_id'];
            }
            $main_dep_data['gender'] = $main_department_list['gender'];
            $main_dep_data['is_tenant_manager'] = $main_department_list['is_tenant_manager'] ? 1 : 0;
            //默认1正常  2离职
            $main_dep_data['status'] = 1;
            if(isset($main_department_list['status']) && !empty($main_department_list['status'])){
                $main_dep_data['is_activated'] = $main_department_list['status']['is_activated'] ? 1 : 0;//是否激活
                $main_dep_data['is_exited'] = $main_department_list['status']['is_exited'] ? 1 : 0;//是否主动退出，主动退出一段时间后用户会自动转为已离职
                $main_dep_data['is_frozen'] = $main_department_list['status']['is_frozen'] ? 1 : 0;//是否暂停
                $main_dep_data['is_resigned'] = $main_department_list['status']['is_resigned'] ? 1 : 0;//是否离职
                $main_dep_data['is_unjoin'] = $main_department_list['status']['is_unjoin'] ? 1 : 0;//是否未加入，需要用户自主确认才能加入团队
                if($main_dep_data['is_resigned'] == 1){
                    $main_dep_data['status'] = 2;
                }
            }
            $main_dep_data['work_station'] = $main_department_list['work_station'];
            //是否集团总部
            if(!empty($main_department_list['department_ids'])){
                $dinfo = Db::name("department")->where(['is_jtzb'=>1])->where(['status'=>1])->where(['department_id'=>['in',$main_department_list['department_ids']]])->find();
                if(!empty($dinfo)){
                    $main_dep_data['is_jtzb'] = 1;
                }
                else{
                    $main_dep_data['is_jtzb'] = 0;
                }
            }
            if(in_array($type,['contact.user.created_v3','contact.user.updated_v3'])){

            }
            elseif(in_array($type,['contact.user.deleted_v3'])){
                $main_dep_data['status'] = 2;
            }
            $userinfo = Db::name("user")->where(['user_id'=>$main_department_list['user_id']])->find();
            if(!empty($userinfo)){
                //离职就删除门禁系统用户信息
                if(isset($main_dep_data['is_jtzb']) && $main_dep_data['is_jtzb'] == 1){
                    if($main_dep_data['status'] == 2){
                        $res = GuardService::instance()->DelPerson($main_department_list['user_id']);
                    }
                    else{
                        $avatar_origin = $main_dep_data['avatar_origin'];
                        if ($userinfo['face_guard_state'] == 1){
                            unset($main_dep_data['avatar_origin']);
                        }
                        /*if(!empty($userinfo['guard_department_id'])){
                            $main_dep_data['department_id'] = $userinfo['guard_department_id'];
                        }
                        else{
                            if(!empty($dinfo)){
                                $main_dep_data['department_id'] = $main_dep_data['guard_department_id'] = $dinfo['department_id'];
                            }
                        }*/
                        if(!empty($dinfo)){
                            $main_dep_data['department_id'] = $main_dep_data['guard_department_id'] = $dinfo['department_id'];
                        }
                        $res = GuardService::instance()->AddPerson($main_dep_data);
                        $main_dep_data['avatar_origin'] = $avatar_origin;
                    }
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        $main_dep_data['update_guard_state'] = 1;
                    }
                    else{
                        $main_dep_data['update_guard_state'] = 0;
                    }
                    $main_dep_data['update_guard_res'] = json_encode($res,304);
                }
                else{
                    $res = GuardService::instance()->getPersoninfo($main_department_list['user_id']);
                    //dump($res);exit;
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        if($main_dep_data['status'] == 2){
                            $res = GuardService::instance()->DelPerson($main_department_list['user_id']);
                        }
                        else{
                            $main_dep_data['guard_department_id'] = $main_dep_data['department_id'] = 3;
                            $res = GuardService::instance()->AddPerson($main_dep_data);
                        }
                        if($res['code'] == 0 && $res['message'] == 'success'){
                            $main_dep_data['update_guard_state'] = 1;
                        }
                        else{
                            $main_dep_data['update_guard_state'] = 0;
                        }
                        $main_dep_data['update_guard_res'] = json_encode($res,304);
                    }
                }
                if (isset($main_dep_data['department_id'])){
                    unset($main_dep_data['department_id']);
                }
                $main_dep_data['update_time'] = $ctime;
                Db::name("user")->where(['id'=>$userinfo['id']])->update($main_dep_data);
            }
            else{
                //集团总部入职就新增门禁系统用户信息
                if(isset($main_dep_data['is_jtzb']) && $main_dep_data['is_jtzb'] == 1 && $main_dep_data['status'] == 1){
                    if(!empty($dinfo)){
                        $main_dep_data['guard_department_id'] = $main_dep_data['department_id'] = $dinfo['department_id'];
                    }
                    $res = GuardService::instance()->AddPerson($main_dep_data);
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        $main_dep_data['update_guard_state'] = 1;
                    }
                    else{
                        $main_dep_data['update_guard_state'] = 0;
                    }
                    $main_dep_data['update_guard_res'] = json_encode($res,304);
                }
                if (isset($main_dep_data['department_id'])){
                    unset($main_dep_data['department_id']);
                }
                $main_dep_data['create_time'] = $main_dep_data['update_time'] = $ctime;
                Db::name("user")->insert($main_dep_data);
            }
        }
    }

    public function is_jtzb($department_id = ''){
        $res_flag = false;
        if(!empty($department_id)){
            $department_ids = getdepartmentids();
            if(in_array($department_id,$department_ids)){
                $res_flag = true;
            }
            $this->GettenantAccessToken();
            $parent_department_url = $this->api_fs_url."/contact/v3/departments/parent?department_id={$department_id}&department_id_type=department_id&page_size={$this->page_size}&user_id_type=user_id";
            $client = new \GuzzleHttp\Client();
            $headers = [
                'Content-Type' => 'application/json;charset=utf-8',
                'Authorization' => 'Bearer '.$this->tenant_access_token
            ];
            $request = $client->get($parent_department_url, [
                'headers' => $headers
            ]);
            $department_lists = json_decode($request->getBody()->getContents(),true);
            //dump($department_lists['data']['items']);exit;
            if($department_lists['code'] == 0){
                //获取二级部门信息
                if(isset($department_lists['data']['items']) && !empty($department_lists['data']['items'])){
                    $parent_department_ids = array_column($department_lists['data']['items'],'department_id');
                    if(count(array_intersect($parent_department_ids, $department_ids)) > 0){
                        $res_flag = true;
                    }
                }
            }
        }
        return $res_flag;
    }

    public function AddEditDepartment($department_id,$type=''){
        $this->GettenantAccessToken();
        $department_url = $this->api_fs_url."/contact/v3/departments/{$department_id}?department_id_type=department_id&user_id_type=user_id";
        $client = new \GuzzleHttp\Client();
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $request = $client->get($department_url, [
            'headers' => $headers
        ]);
        $departmentinfos = json_decode($request->getBody()->getContents(),true);
        //dump($departmentinfos);exit;
        if($departmentinfos['code'] == 0 && isset($departmentinfos['data']['department']) && !empty($departmentinfos['data']['department'])){
            $main_department_list = $departmentinfos['data']['department'];
            $ctime = time();
            $main_dep_data = [];
            $main_dep_data['department_id'] = $main_department_list['department_id'];
            $main_dep_data['title'] = $main_department_list['name'];
            if(isset($main_department_list['leader_user_id']) && !empty($main_department_list['leader_user_id'])){
                $main_dep_data['leader_user_id'] = $main_department_list['leader_user_id'];
            }
            if(isset($main_department_list['leaders']) && !empty($main_department_list['leaders'])){
                $main_dep_data['leaders'] = json_encode($main_department_list['leaders'],304);
            }
            $main_dep_data['member_count'] = $main_department_list['member_count'];
            $main_dep_data['primary_member_count'] = $main_department_list['primary_member_count'];
            $main_dep_data['open_department_id'] = $main_department_list['open_department_id'];
            $main_dep_data['pid'] = $main_dep_data['parent_department_id'] = $main_department_list['parent_department_id'];
            $main_dep_data['sort'] = $main_department_list['order'];
            $main_dep_data['status'] = isset($main_department_list['status']['is_deleted']) && $main_department_list['status']['is_deleted'] ? -1 : 1;
            if($main_dep_data['status'] == 1 && $type == 'contact.department.deleted_v3'){
                $main_dep_data['status'] = -1;
            }
            //是否属于集团总部
            $main_dep_data['is_jtzb'] = 0;
            if($this->is_jtzb($main_department_list['department_id'])){
                $main_dep_data['is_jtzb'] = 1;
            }
            //dump($main_dep_data);exit;
            $departinfo = Db::name("department")->where(['department_id'=>$main_department_list['department_id']])->find();
            //dump($departinfo);exit;
            if(!empty($departinfo)){
                //删除门禁系统集团总部部门
                if($main_dep_data['is_jtzb'] == 1){
                    //dump($main_dep_data['status']);exit;
                    if($main_dep_data['status'] == -1){
                        //先转移当前部门的用户信息
                        $where = [];
                        $where['update_guard_state'] = $where['status'] = 1;
                        $where['guard_department_id'] = $main_department_list['department_id'];
                        $userlists = Db::name("user")->where($where)->select();
                        if(!empty($userlists)){
                            foreach ($userlists as $row){
                                $this->AddEditUser($row['user_id'],"contact.user.updated_v3");
                            }
                        }
                        $res = GuardService::instance()->DelDepartment($main_department_list['department_id']);
                    }
                    else{
                        $res = GuardService::instance()->AddDepartment($departinfo);
                    }
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        $main_dep_data['update_guard_state'] = 1;
                    }
                    else{
                        $main_dep_data['update_guard_state'] = 0;
                    }
                    $main_dep_data['update_guard_res'] = json_encode($res,304);
                }
                else{
                    if(!in_array($main_department_list['department_id'],specialdepartmentids())){
                        //先转移当前部门的用户信息
                        $where = [];
                        $where['update_guard_state'] = $where['status'] = 1;
                        $where['guard_department_id'] = $main_department_list['department_id'];
                        $userlists = Db::name("user")->where($where)->select();
                        if(!empty($userlists)){
                            foreach ($userlists as $row){
                                $this->AddEditUser($row['user_id'],"contact.user.updated_v3");
                            }
                        }
                        $res = GuardService::instance()->DelDepartment($main_department_list['department_id']);
                    }
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        $main_dep_data['update_guard_state'] = 1;
                    }
                    else{
                        $main_dep_data['update_guard_state'] = 0;
                    }
                    $main_dep_data['update_guard_res'] = json_encode($res,304);
                }
                $main_dep_data['update_time'] = $ctime;
                Db::name("department")->where(['id'=>$departinfo['id']])->update($main_dep_data);
            }
            else{
                //新增门禁系统集团总部部门
                if($main_dep_data['is_jtzb'] == 1){
                    $res = GuardService::instance()->AddDepartment($main_dep_data);
                    if($res['code'] == 0 && $res['message'] == 'success'){
                        $main_dep_data['update_guard_state'] = 1;
                    }
                    else{
                        $main_dep_data['update_guard_state'] = 0;
                    }
                    $main_dep_data['update_guard_res'] = json_encode($res,304);
                }
                $main_dep_data['create_time'] = $main_dep_data['update_time'] = $ctime;
                Db::name("department")->insert($main_dep_data);
            }
        }
    }

    public function GetuserBydeparmentid($department_id,$ctime,$page_token = ''){
        $this->GettenantAccessToken();
        $find_by_department_url = $this->api_fs_url."/contact/v3/users/find_by_department?department_id={$department_id}&department_id_type=department_id&page_size={$this->page_size}&user_id_type=user_id&page_token={$page_token}";
        $client = new \GuzzleHttp\Client();
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $request = $client->get($find_by_department_url, [
            'headers' => $headers
        ]);
        $department_lists = json_decode($request->getBody()->getContents(),true);
        //dump($department_lists['data']['items']);exit;
        //写入数据库
        if(isset($department_lists['data']['items'])){
            //dump($department_lists['data']['items'][1]);exit;
            //$ctime = time();
            try {
                foreach ($department_lists['data']['items'] as $main_department_list) {
                    $main_dep_data = [];
                    $main_dep_data['user_id'] = $main_department_list['user_id'];
                    $main_dep_data['username'] = $main_department_list['name'];
                    $main_dep_data['open_id'] = $main_department_list['open_id'];
                    $main_dep_data['union_id'] = $main_department_list['union_id'];
                    if (isset($main_department_list['mobile']) && !empty($main_department_list['mobile'])) {
                        $main_dep_data['mobile_origin'] = $main_department_list['mobile'];
                        $main_dep_data['mobile'] = str_replace('+86', '', $main_department_list['mobile']);
                    } else {
                        $main_dep_data['mobile'] = "";
                        //dump($main_department_list);exit;
                    }
                    $main_dep_data['mobile_visible'] = $main_department_list['mobile_visible'] ? 1 : 0;
                    $main_dep_data['department_ids'] = isset($main_department_list['department_ids']) && !empty($main_department_list['department_ids']) ? implode(",", $main_department_list['department_ids']) : '';
                    //头像
                    if (isset($main_department_list['avatar']) && !empty($main_department_list['avatar'])) {
                        $main_dep_data['avatar_origin'] = isset($main_department_list['avatar']['avatar_origin']) ? $main_department_list['avatar']['avatar_origin'] : '';
                        $main_dep_data['avatar_240'] = isset($main_department_list['avatar']['avatar_240']) ? $main_department_list['avatar']['avatar_240'] : '';
                        $main_dep_data['avatar_640'] = isset($main_department_list['avatar']['avatar_640']) ? $main_department_list['avatar']['avatar_640'] : '';
                        $main_dep_data['avatar_72'] = isset($main_department_list['avatar']['avatar_72']) ? $main_department_list['avatar']['avatar_72'] : '';
                    }
                    //排序
                    if (isset($main_department_list['orders']) && !empty($main_department_list['orders'])) {
                        Db::name("user_orders")->where(['user_id'=>$main_department_list['user_id']])->update(['update_state'=>0]);
                        foreach ($main_department_list['orders'] as $order) {
                            $order_data = [];
                            $order_data['user_id'] = $main_department_list['user_id'];
                            $order_data['department_id'] = $order['department_id'];
                            $order_data['department_order'] = $order['department_order'];
                            $order_data['is_primary_dept'] = $order['is_primary_dept'] ? 1 : 0;;
                            $order_data['user_order'] = $order['user_order'];
                            $order_data['update_state'] = 1;
                            //dump($order_data);exit;
                            $orderinfo = Db::name("user_orders")->where(['user_id' => $order_data['user_id']])->where(['department_id' => $order_data['department_id']])->find();
                            if (!empty($orderinfo)) {
                                Db::name("user_orders")->where(['id' => $orderinfo['id']])->update($order_data);
                            } else {
                                Db::name("user_orders")->insert($order_data);
                            }
                        }
                    }
                    $main_dep_data['employee_no'] = $main_department_list['employee_no'];
                    $main_dep_data['employee_type'] = $main_department_list['employee_type'];
                    $main_dep_data['job_title'] = $main_department_list['job_title'];
                    $main_dep_data['join_time'] = $main_department_list['join_time'];
                    if (isset($main_department_list['leader_user_id']) && !empty($main_department_list['leader_user_id'])) {
                        $main_dep_data['leader_user_id'] = $main_department_list['leader_user_id'];
                    }
                    $main_dep_data['gender'] = $main_department_list['gender'];
                    $main_dep_data['is_tenant_manager'] = $main_department_list['is_tenant_manager'] ? 1 : 0;
                    //默认1正常  2离职
                    $main_dep_data['status'] = 1;
                    if (isset($main_department_list['status']) && !empty($main_department_list['status'])) {
                        $main_dep_data['is_activated'] = $main_department_list['status']['is_activated'] ? 1 : 0;
                        $main_dep_data['is_exited'] = $main_department_list['status']['is_exited'] ? 1 : 0;
                        $main_dep_data['is_frozen'] = $main_department_list['status']['is_frozen'] ? 1 : 0;
                        $main_dep_data['is_resigned'] = $main_department_list['status']['is_resigned'] ? 1 : 0;
                        $main_dep_data['is_unjoin'] = $main_department_list['status']['is_unjoin'] ? 1 : 0;
                        if($main_dep_data['is_resigned'] == 1){
                            $main_dep_data['status'] = 2;
                        }
                    }
                    $main_dep_data['is_jtzb'] = 1;
                    $main_dep_data['work_station'] = $main_department_list['work_station'];
                    //dump($main_dep_data);continue;
                    $userinfo = Db::name("user")->where(['user_id' => $main_department_list['user_id']])->find();
                    $msg_type = "新增";
                    if(!empty($userinfo)){
                        //离职就删除门禁系统用户信息
                        if($main_dep_data['status'] == 2){
                            $res = GuardService::instance()->DelPerson($main_department_list['user_id']);
                            if($res['code'] == 0 && $res['message'] == 'success'){
                                $main_dep_data['update_guard_state'] = 1;
                            }
                            else{
                                $main_dep_data['update_guard_state'] = 0;
                            }
                            $main_dep_data['update_guard_res'] = json_encode($res,304);
                        }
                        else{
                            $main_dep_data['guard_department_id'] = $main_dep_data['department_id'] = $department_id;
                            if (!empty($main_dep_data['mobile']) && strlen($main_dep_data['mobile']) == 11) {
                                $avatar_origin = $main_dep_data['avatar_origin'];
                                if ($userinfo['face_guard_state'] == 1){
                                    unset($main_dep_data['avatar_origin']);
                                }
                                $res = GuardService::instance()->AddPerson($main_dep_data);
                                if($res['code'] == 0 && $res['message'] == 'success'){
                                    $main_dep_data['update_guard_state'] = 1;
                                }
                                else{
                                    $main_dep_data['update_guard_state'] = 0;
                                }
                                $main_dep_data['update_guard_res'] = json_encode($res,304);
                                $main_dep_data['avatar_origin'] = $avatar_origin;
                            }
                            else{
                                $main_dep_data['update_guard_state'] = 0;
                                $main_dep_data['update_guard_res'] = "";
                            }
                        }
                        if (isset($main_dep_data['department_id'])){
                            unset($main_dep_data['department_id']);
                        }
                        $main_dep_data['update_time'] = $ctime;
                        Db::name("user")->where(['id'=>$userinfo['id']])->update($main_dep_data);
                        $msg_type = "更新";
                    }
                    else{
                        //集团总部入职就新增门禁系统用户信息
                        if(isset($main_dep_data['is_jtzb']) && $main_dep_data['is_jtzb'] == 1 && $main_dep_data['status'] == 1){
                            $main_dep_data['guard_department_id'] = $main_dep_data['department_id'] = $department_id;
                            if (!empty($main_dep_data['mobile']) && strlen($main_dep_data['mobile']) == 11) {
                                $res = GuardService::instance()->AddPerson($main_dep_data);
                                if($res['code'] == 0 && $res['message'] == 'success'){
                                    $main_dep_data['update_guard_state'] = 1;
                                }
                                else{
                                    $main_dep_data['update_guard_state'] = 0;
                                }
                                $main_dep_data['update_guard_res'] = json_encode($res,304);
                            }
                            else{
                                $main_dep_data['update_guard_state'] = 0;
                                $main_dep_data['update_guard_res'] = "";
                            }
                        }
                        if (isset($main_dep_data['department_id'])){
                            unset($main_dep_data['department_id']);
                        }
                        $main_dep_data['create_time'] = $main_dep_data['update_time'] = $ctime;
                        Db::name("user")->insert($main_dep_data);
                    }

                    /*$msg_type = "新增";
                    if (!empty($userinfo)) {
                        $main_dep_data['update_time'] = $ctime;
                        Db::name("user")->where(['id' => $userinfo['id']])->update($main_dep_data);
                        $msg_type = "更新";
                    } else {
                        $main_dep_data['create_time'] = $main_dep_data['update_time'] = $ctime;
                        Db::name("user")->insert($main_dep_data);
                    }

                    //更新门禁系统用户信息
                    if (!empty($main_dep_data['mobile']) && strlen($main_dep_data['mobile']) == 11) {
                        $main_dep_data['department_id'] = $department_id;
                        if(!empty($userinfo) && $userinfo['face_guard_state'] == 1){
                            unset($main_dep_data['avatar_origin']);
                        }
                        $res = GuardService::instance()->AddPerson($main_dep_data);
                        if ($res['code'] == 0 && $res['message'] == 'success') {
                            $main_dep_data['update_guard_state'] = 1;
                        } else {
                            $main_dep_data['update_guard_state'] = 0;
                        }
                        $main_dep_data['update_guard_res'] = json_encode($res, 304);
                        unset($main_dep_data['department_id']);
                        Db::name("user")->where(['user_id' => $main_department_list['user_id']])->update(['guard_department_id'=>$department_id,'update_guard_state'=>$main_dep_data['update_guard_state'],'update_guard_res'=>$main_dep_data['update_guard_res']]);
                    }
                    else{
                        Db::name("user")->where(['user_id' => $main_department_list['user_id']])->update(['guard_department_id'=>$department_id,'update_guard_state'=>0,'update_guard_res'=>'','face_guard_state'=>0]);
                    }*/
                    echo $this->count++ . "---" . $msg_type . "---" . $ctime . "---" . $main_dep_data['user_id'] . PHP_EOL;
                }
            }
            catch (Exception $exception){
                dump($exception->getMessage());
            }
        }
        if($department_lists['code'] == 0 && isset($department_lists['data']['has_more']) && $department_lists['data']['has_more'] && !empty($department_lists['data']['page_token'])){
            $this->GetuserBydeparmentid($department_id,$ctime,$department_lists['data']['page_token']);
        }
    }

    public function GetchildrendepByfdepid($department_id,$ctime,$page_token = ''){
        $this->GettenantAccessToken();
        $departments_children_url = $this->api_fs_url."/contact/v3/departments/{$department_id}/children?department_id_type=department_id&fetch_child=true&page_size={$this->page_size}&user_id_type=user_id&page_token={$page_token}";
        $client = new \GuzzleHttp\Client();
        $headers = [
            'Content-Type' => 'application/json;charset=utf-8',
            'Authorization' => 'Bearer '.$this->tenant_access_token
        ];
        $request = $client->get($departments_children_url, [
            'headers' => $headers
        ]);
        //echo $request->getBody()->getContents();exit;
        $department_lists = json_decode($request->getBody()->getContents(),true);
        //dump($department_lists);exit;
        //写入数据库
        if(isset($department_lists['data']['items'])){
            //$ctime = time();
            foreach ($department_lists['data']['items'] as $main_department_list) {
                //dump($main_department_list);
                //continue;
                $main_dep_data = [];
                $main_dep_data['department_id'] = $main_department_list['department_id'];
                $main_dep_data['title'] = $main_department_list['name'];
                if(isset($main_department_list['leader_user_id']) && !empty($main_department_list['leader_user_id'])){
                    $main_dep_data['leader_user_id'] = $main_department_list['leader_user_id'];
                }
                if(isset($main_department_list['leaders']) && !empty($main_department_list['leaders'])){
                    $main_dep_data['leaders'] = json_encode($main_department_list['leaders'],304);
                }
                $main_dep_data['member_count'] = $main_department_list['member_count'];
                $main_dep_data['primary_member_count'] = $main_department_list['primary_member_count'];
                $main_dep_data['open_department_id'] = $main_department_list['open_department_id'];
                $main_dep_data['pid'] = $main_dep_data['parent_department_id'] = $main_department_list['parent_department_id'];
                $main_dep_data['sort'] = $main_department_list['order'];
                $main_dep_data['status'] = isset($main_department_list['status']['is_deleted']) && $main_department_list['status']['is_deleted'] ? -1 : 1;
                $main_dep_data['is_jtzb'] = 1;
                $main_dep_data['update_state'] = 1;
                $res = GuardService::instance()->AddDepartment($main_dep_data);
                if($res['code'] == 0 && $res['message'] == 'success'){
                    $main_dep_data['update_guard_state'] = 1;
                }
                else{
                    $main_dep_data['update_guard_state'] = 0;
                }
                $main_dep_data['update_guard_res'] = json_encode($res,304);
                $departinfo = Db::name("department")->where(['department_id'=>$main_department_list['department_id']])->find();
                $msg_type = "新增";
                if(!empty($departinfo)){
                    $main_dep_data['update_time'] = $ctime;
                    Db::name("department")->where(['id'=>$departinfo['id']])->update($main_dep_data);
                    $msg_type = "更新";
                }
                else{
                    $main_dep_data['create_time'] = $main_dep_data['update_time'] = $ctime;
                    Db::name("department")->insert($main_dep_data);
                }
                echo $this->count++."---".$msg_type."---".$ctime."---".$main_dep_data['department_id'].PHP_EOL;
            }
        }
        if($department_lists['code'] == 0 && isset($department_lists['data']['has_more']) && $department_lists['data']['has_more'] && !empty($department_lists['data']['page_token'])){
            $this->GetchildrendepByfdepid($department_id,$ctime,$department_lists['data']['page_token']);
        }
    }


}